package com.ship.dispatch.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.SpFobSublease;
import com.ship.dispatch.service.ExportService;
import com.ship.dispatch.service.SpFobSubleaseService;
import com.ship.system.api.RemoteUserService;
import com.ship.system.api.domain.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/spFobSublease/")
@Api(value = "spFobSublease", tags = "商务执行")
public class SpFobSubleaseController {

    @Autowired
    SpFobSubleaseService spFobSubleaseService;

    @Autowired(required = false)
    RemoteUserService remoteUserService;

    @Autowired
    private ExportService exportService;
    @PostMapping("/page")
    @ApiOperation(value = "商务执行分页")
    public JsonResult<Page<SpFobSublease>> page(@RequestBody SpFobSublease pageDto){
        Page<SpFobSublease> resultPage = spFobSubleaseService.page(pageDto);
        List<SpFobSublease> executes = resultPage.getList();
        if(executes.size()>0){
            executes.forEach(item->{
                if(item.getAssigeners()!=null && item.getAssigeners().length()>0){
                   // String[] ids = item.getAssigeners().split(",");
                   // List<Long> userIds = Arrays.stream(ids).map(s->Long.parseLong(s)).collect(Collectors.toList());
                    List<SysUser> users = remoteUserService.listByIds( item.getAssigeners());

                    StringBuilder builder = new StringBuilder();
                    for(SysUser user:users){
                        builder.append(user.getNickName()).append(",");
                    }
                    String result = builder.toString();
                    if(result.endsWith(",")) {
                        result = result.substring(0, result.lastIndexOf(","));
                    }
                    item.setAssigeners(result);
                }
            });
        }
        resultPage.setList(executes);
        return JsonResult.success(resultPage);
    }

    /**
     * 船运执行方案下发执行列表
     * @param dto
     * @return
     */
    @ApiOperation(value = "商务执行导出")
    @PostMapping("/page/export")
    @Log(title = "导出船运执行方案下发执行列表",businessType = BusinessType.EXPORT)
    public JsonResult pageExport(@RequestBody SpFobSublease dto){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(dto.getIds() != null && dto.getIds().size() > 0){
            queryWrapper.in("id",dto.getIds());
        }
        List<SpFobSublease> exportList = spFobSubleaseService.pageExportList(dto, queryWrapper, new LinkedList<>());
        for (SpFobSublease dispatchSchemeExecute : exportList) {
            dispatchSchemeExecute.setTradeBodyStr(dispatchSchemeExecute.getTradeBodyStr());
            dispatchSchemeExecute.setStatusStr(dispatchSchemeExecute.getStatusStr());

            if(dispatchSchemeExecute.getContractType()!=null){
                String result = null;
                if(dispatchSchemeExecute.getContractType()==1){
                    result = "租入长期船";
                }else if(dispatchSchemeExecute.getContractType()==2){
                    result = "租入短期船";
                }else if(dispatchSchemeExecute.getContractType()==3){
                    result = "船舶租出";
                }else if(dispatchSchemeExecute.getContractType()==4){
                    result = "内部转租";
                }
                dispatchSchemeExecute.setContractTypeStr(result);
            }

            if(dispatchSchemeExecute.getAssigeners()!=null && dispatchSchemeExecute.getAssigeners().length()>0){
                // String[] ids = item.getAssigeners().split(",");
                // List<Long> userIds = Arrays.stream(ids).map(s->Long.parseLong(s)).collect(Collectors.toList());
                List<SysUser> users = remoteUserService.listByIds( dispatchSchemeExecute.getAssigeners());

                StringBuilder builder = new StringBuilder();
                for(SysUser user:users){
                    builder.append(user.getNickName()).append(",");
                }
                String result = builder.toString();
                if(result.endsWith(",")) {
                    result = result.substring(0, result.lastIndexOf(","));
                }
                dispatchSchemeExecute.setAssigeners(result);
            }
        }
        Field[] fields = SpFobSublease.class.getDeclaredFields();
        String url = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sp_fob_sublease", SecurityUtils.getUserId()), "商务执行详情");
        String CsoldPart = "http://10.75.34.224:9300/statics";
        String ZsoldPart = "http://10.75.33.149:9300/statics";
        String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
        String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";
        String newUrl = "";
        if (url.contains("http://10.75.34.224:9300/statics")) {
            newUrl = url.replace(CsoldPart, CsPart);
        }else if (url.contains("http://10.75.33.149:9300/statics")){
            newUrl = url.replace(ZsoldPart, ZsPart);
        }else {
            newUrl = url;
        }
        return JsonResult.success(newUrl);
    }

    @DeleteMapping("/remove/{id}")
    @Log(title = "删除执行记录ID",businessType = BusinessType.DELETE)
    public JsonResult deleteExecute(@PathVariable("id") Long id){
        spFobSubleaseService.removeById(id);
        return JsonResult.success();
    }

}
